package com.woniuxy.happylife.order.consumer;

import com.rabbitmq.client.Channel;
import com.woniuxy.happylife.entity.MallOrder;
import com.woniuxy.happylife.entity.Order;
import com.woniuxy.happylife.order.dao.OrderDao;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @Title: Consumer
 * @ProjectName: redis-rabbitmq
 * @Description: TODO
 * @Author: chowinggum
 * @Date: 2022/1/13 12:07
 */
@Component
public class Consumer {
    @Autowired
    RedisTemplate redisTemplate;
    @Resource
    OrderDao orderDao;
    @RabbitListener(queues = {"diequeue"})
    public void receiveAdd(Order order, Message message, Channel channel) throws Exception {
        System.out.println("队列处理，添加数据库时间"+new Date());
        System.out.println("order:"+order);
        int uid = order.getUid();
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String status = valueOperations.get(uid + "").toString();
        if(Integer.parseInt(status)==1){
           System.out.println("添加到数据库");
            order.setStatus(1);
           orderDao.add(order);

       }else{
            //抢单未支付，商品回滚库存加一
            redisTemplate.opsForValue().increment("stock");
        }

        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        System.out.println("------------------------");
    }

}
